<template>
    <el-card header="备忘录" size="small">
        <template #header>
            <div style="display: flex;align-items: center;">
                备忘录&nbsp;&nbsp;
                <el-radio-group v-model="state.params.view" size="small">
                    <el-radio-button label="日历" value="" />
                    <el-radio-button label="表格" value="table" />
                </el-radio-group>
                &nbsp;&nbsp;
                <el-button size="small" type="success" @click="onEdit('')">添加</el-button>
                <template v-if="state.authHide">
                    <el-button size="small" type="info" @click="onAuth">授权通知</el-button>
                    &nbsp;首次使用一定要点授权通知
                </template>
            </div>
        </template>

        
        <!-- 表格 -->
        <el-table v-if="state.params.view === 'table'" :data="state.data" style="width: 100%;" border>
            <el-table-column label="通知" prop="title"></el-table-column>
            <el-table-column label="消息" prop="message"></el-table-column>
            <el-table-column label="链接" prop="url"></el-table-column>
            <el-table-column label="级别" prop="level"></el-table-column>
            <el-table-column label="日期" prop="date">
                <template #default="scope">{{ scope.row.date.toLocaleString() }}</template>
            </el-table-column>
            <el-table-column label="操作" prop="handle">
                <template #default="scope">
                    <el-button-group>
                        <el-button size="small" type="primary" @click="onEdit(getYmd(scope.row.date))">编辑</el-button>
                        <el-button size="small" type="danger" @click="onDel(getYmd(scope.row.date))">删除</el-button>
                        <el-button size="small" type="warning" @click="onTrigger(getYmd(scope.row.date))">通知</el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>
        <el-calendar v-else v-model="state.selectedDate">
            <template #date-cell="{ data }">
                <div :class="data.isSelected ? 'is-selected' : ''" style="position: relative;">
                    {{ data.day.split('-').slice(1).join('-') }}
                    <div v-if="data.day in state.keys" style="display: flex;align-items: center;justify-content: space-between;margin-top:5px;">
                        <el-tag style="position: absolute;top:0px;right:0px;" :type="state.keys[data.day].level">{{ state.keys[data.day].title }}</el-tag>
                       {{ state.keys[data.day].message }}
                    </div>

                    <div style="text-align: right;">
                        <template v-if="data.isSelected || memoShow(data.day)">
                            <el-icon title="编辑" @click="onEdit(data.day)"><Edit /></el-icon>
                        </template>
                        <el-icon title="删除" v-if="memoShow(data.day)" 
                        @click="onDel(data.day)" style="color:brown;margin-left:2px;"><Delete /></el-icon>
                    </div>
                </div>
            </template>
        </el-calendar>
        
        <el-dialog
            v-model="state.dialogVisible"
            title="修改备忘录"
            width="50vw"
        >
        <template #footer>
            <!-- 表单 -->
            <el-form ref="formRef" :model="state.form" :rules="state.rules"  label-width="auto">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="state.form.title" placeholder="标题"></el-input>
                </el-form-item>
                <el-form-item label="消息" prop="message">
                    <el-input v-model="state.form.message" placeholder="消息"></el-input>
                </el-form-item>
                <el-form-item label="链接" prop="url">
                    <el-input v-model="state.form.url" placeholder="链接"></el-input>
                </el-form-item>
                <el-form-item label="日期" prop="date">
                    <el-date-picker
                        v-model="state.form.date"
                        type="datetime"
                        placeholder="请选择日期"
                    />
                </el-form-item>
                <el-form-item label="级别" prop="level">
                    <el-select v-model="state.form.level">
                        <el-option label="日常" value="info"></el-option>
                        <el-option label="维护" value="warning"></el-option>
                        <el-option label="任务" value="primary"></el-option>
                        <el-option label="续费" value="danger"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div class="dialog-footer">
                <el-button @click="state.dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="onSubmit">确定</el-button>
            </div>
            </template>
        </el-dialog>
    </el-card>
</template>
<script setup lang="ts">
import { ElMessage, ElForm, ElMessageBox } from 'element-plus';
import { onMounted, reactive, ref, computed  } from 'vue'
import Memo, { getYmd } from "../../utils/memo"
import type { MemoInfo} from '../../types/memo.types'
import {OpenUrl} from '../../../wailsjs/go/main/App'

const formRef = ref(ElForm)

interface KeysType { 
    [key: string]: MemoInfo;
}

const initData: MemoInfo = {
    title: '通知',
    message: '云服务器快到期了',
    url: 'https://www.aliyun.com/',
    date: new Date(),
    level: 'info',
    time: 0,
}

const state = reactive({
    dialogVisible: false,
    data: [] as MemoInfo[],
    keys: {} as KeysType,
    selectedDate: new Date(),
    authHide: false, // 授权通知隐藏
    params: {
        view: '',
    },
    form: {
        ...initData,
    },
    rules: {
        title: [
            { required: true, message: '请输入标题', trigger: 'blur' },
            { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
        ],
        message: [
            { required: true, message: '请输入消息', trigger: 'blur' },
            { min: 2, max: 200, message: '长度在 3 到 200 个字符', trigger: 'blur' },
        ],
        date: [
            { required: true, message: '请选择日期', trigger: 'change' },
        ],
        level: [
            { required: true, message: '请选择级别', trigger: 'change' },
        ],
    }
})

let timer: any;

onMounted(( ) => {
    state.authHide = window.Notification && Notification.permission != "granted";
    init();

    if (timer) clearInterval(timer);
    checkNotify();
    timer = setInterval(() => {
        console.log('checkNotify');
        checkNotify();
    }, 1000 * 60 * 5); // 每5分钟检测一次
})

// 初始化 数据
const init = () => {
    state.data = Memo.getAll();
    const keys: KeysType = {}
    state.data.forEach(item => {
        keys[getYmd(item.date)] = item
    })
    state.keys = keys;
}

// 检测是否有近两日的通知
const checkNotify = () => {
    const now = Date.now();
    const keys = Object.keys(state.keys);
    for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        const memo = state.keys[key];
        if (memo.time - 0 - 24 * 3600 * 4 <= now || memo.time - 0 - 24 * 3600 * 2 >= now) {
            const day = getYmd(memo.date);
            setTimeout(() => {
                onTrigger(day);
            }, i * 1000 * 10);
        }
    }
}

const memoShow = computed(() => {
    return (day: string):boolean => {
        return state.keys[day] ? true : false;
    }
})

// 授权通知
const onAuth = () => { 
    if (window.Notification && Notification.permission !== "granted") {
        Notification.requestPermission(function(status) {
          if (Notification.permission !== status) {
            // @ts-ignore
            Notification.permission = status;
          }
        });
    }
}

// 编辑
const onEdit = (day: string) => {
    state.dialogVisible = true;
    if (day && state.keys[day]) {
        state.form = state.keys[day];
        ElMessage.info('编辑备忘录');
    } else {
        state.form = {...initData}
        state.form.date = day ? new Date(day) : new Date();
        state.form.time = state.form.date.getTime();
        ElMessage.info('新增备忘录');
    }
}

// 删除
const onDel = (day: string) => {
    if (!day || !state.keys[day]) {
        return ElMessage.error('请选择备忘录');
    }
    ElMessageBox.confirm(
        `删除${day}：${state.keys[day].message}?`,
        state.keys[day].title,
        {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
        }
    )
    .then(() => {
        Memo.delete(state.keys[day]);
        delete state.keys[day];

        init();
        ElMessage({
            type: 'success',
            message: '删除成功',
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 提交
const onSubmit = () => {
    formRef.value.validate((valid:Boolean) => {
        if (!valid) {
            ElMessage.error('请检查输入项');
        }

        state.form.time = state.form.date.getTime();
        
        Memo.edit(state.form);
        const ymd = getYmd(state.form.date)
        if (!state.keys[ymd]) {
            state.data.push(state.form);
        }
        ElMessage.success('保存成功');
        state.dialogVisible = false;
        init();
    });
}

// 通知
const onTrigger = (day: string) => {
    if (!day || !state.keys[day]) return ElMessage.error('请选择备忘录');
    if (!window.Notification || Notification.permission !== "granted") return ElMessage.error('无法发送通知，请授权');
    
    const memo = state.keys[day];
    const now = Date.now();
    const mu = Math.floor(Math.abs(memo.time - now) / 1000);
    const hour = Math.floor(mu / 3600 * 10) / 10;
    const n = new Notification(state.keys[day].title, {
        body: state.keys[day].message + ' 倒计时:' + hour + '小时',
        requireInteraction: true,
        icon: "https://tse2-mm.cn.bing.net/th/id/OIP-C.7pmotRzx9Y73PO4ax0dmhAHaHa?w=186&h=186&c=7&r=0&o=5&pid=1.7", // 可选的图标URL
        data: { url: state.keys[day].url ?? '' } // 传递跳转的URL
    });
    n.onclick = () => {
        n.close(); // 关闭通知
        if (n.data.url) {
            OpenUrl(n.data.url);
            ElMessage.success('点击了通知，跳转网址中..' + n.data.url);
        } else ElMessage.success('点击了通知');
    }
    ElMessage.success('通知发送成功');
}

</script>
<style>
.is-selected {
    color: #1989fa;
}
</style>
  